/*
 * @Author: shiguo
 * @Date: 2022-07-27 15:37:36
 * @LastEditors: shiguo
 * @LastEditTime: 2022-09-14 15:08:43
 * @FilePath: /@aks-dev/taro-h5/lib/RefreshList/index.tsx
 */
import { View } from '@tarojs/components';
import { DotLoading, InfiniteScroll, PullToRefresh } from 'antd-mobile';
import * as React from 'react';
import type { RefreshListProps } from '../../types/RefreshList';
export const RefreshList: React.FC<RefreshListProps> =
    (props) => {

        const containerRef = React.useRef<HTMLElement>()
        const [w, setW] = React.useState<number>(0)
        React.useLayoutEffect(() => {
            setTimeout(() => {
                setW(containerRef.current?.clientWidth || 0)
            }, 350)
        }, [])


        return (
            <View style={{
                display: 'flex',
                flexGrow: 1,
                overflowY: 'scroll',
                overflowX: 'hidden',
                flexDirection: 'column',
                alignItems: 'center',
                // justifyContent: 'center',

                ...props.style
            }}
                ref={containerRef}
            >
                <PullToRefresh
                    onRefresh={props.onHeaderRefresh}
                >
                    <div style={{
                        width:`${w}px`,
                        // background:'purple',
                        ...styles.item,
                        ...props.containerStyle,
                    }}>

                        {props.children}
                    </div>
                    {
                        props.onFooterRefresh &&
                        <InfiniteScroll loadMore={props.onFooterRefresh} hasMore={props.hasMore as boolean} >
                            {infiniteScrollContent}
                        </InfiniteScroll>

                    }

                </PullToRefresh>
            </View>

        )
    }


const infiniteScrollContent: (
    hasMore: boolean,
    failed: boolean,
    retry: () => void
) => React.ReactNode

    = (hasMore, failed, retry) => {


        if (failed) return (
            <span style={styles.span} onClick={() => retry()}>网络请求失败，请点击重试加载！</span>
        )

        if (hasMore) return (
            <>
                <span style={styles.span}>加载中</span>
                <DotLoading />
            </>
        )

        return (
            <span style={styles.span}>--- 已经到底部了 ---</span>
        )

    }



const styles: Record<string, React.CSSProperties> = {
    item: {
        display: 'flex',
        flexDirection: 'column',
    },
    span: {
        color: '#999999',
        fontSize: '12px'
    }
}



